package com.woniuxy.woniuticket.financemodule.controller;
/**
 * 懒得写service了，就都写controller了
 */

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.woniuxy.woniuticket.financemodule.entity.PayArg;
import com.woniuxy.woniuticket.financemodule.entity.QueryArg;
import com.woniuxy.woniuticket.financemodule.entity.RefundArg;
import com.woniuxy.woniuticket.ordermodule.service.OrderService;
import com.woniuxy.woniuticket.pojo.CinemaOder;
import com.woniuxy.woniuticket.pojo.UsersInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/zilanxuan")
@PropertySource({"classpath:paycfg.properties"})
public class PayController {
	
	/** appid*/
	@Value("2016092800618555")
	public String App_id;
	
	/** 应用私钥*/
	@Value("${merchant_private_key}")
	public String Merchant_private_key;
	
	/** 支付宝公钥 */
	@Value("${alipay_public_key}")
	public String Alipay_public_key;
	
	/** 异步通知url*/
	@Value("${notify_url}")
	public String Notify_url;
	
	/* * 同步通知url*/
	@Value("${return_url}/")
	public String Return_url;
	
	/** 加密类型*/
	@Value("${sign_type}")
	public String Sign_type;
	
	/** 字符集*/
	@Value("${charset}")
	public String Charset;
	
	/** 应用网关*/
	@Value("${gatewayUrl}")
	public String GatewayUrl;
	
	/** 日志路径*/
	@Value("${log_path}")
	public String Log_path;

	private AlipayClient alipayClient = null;

	private String result = null;

	@Resource
    private OrderService orderService;   //订单支付service

	/**
	 * 支付接口(沙箱测试)
	 * @param p 支付接口参数对象 (自己封装)
	 * @return
	 */

	@RequestMapping("/pay")
	@ResponseBody
	public String pay(PayArg p,HttpSession session) {
		System.out.println("订单号："+p.getTradeNo());
		session.setAttribute("payinfo",p);
		alipayClient = new DefaultAlipayClient(GatewayUrl, App_id, Merchant_private_key, "json", Charset, Alipay_public_key, Sign_type);
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(Return_url);
		alipayRequest.setNotifyUrl(Notify_url);
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ p.getTradeNo() +"\"," 
				+ "\"total_amount\":\""+ p.getTotalAmount() +"\"," 
				+ "\"subject\":\""+ p.getSubject() +"\"," 
				+ "\"body\":\""+ p.getBody() +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		try {
			result = alipayClient.pageExecute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		//输出
		System.out.println("付款成功"+result);
		return result;
	}
	
	/**
	 * 退款接口:退款执行的页面
	 * @return
	 */
	@RequestMapping(value="/refund",method= RequestMethod.POST)
	public String refund(@ModelAttribute RefundArg refund,String newOderNum, HttpSession session) {
		System.out.println("退款接口："+refund+"新订单号："+newOderNum);
		//获得初始化的AlipayClient
		alipayClient = new DefaultAlipayClient(GatewayUrl, App_id, Merchant_private_key, "json", Charset, Alipay_public_key, Sign_type);
		//设置请求参数
		AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ refund.getOut_trade_no() +"\"," 
				+ "\"trade_no\":\""+ refund.getTrade_no() +"\"," 
				+ "\"refund_amount\":\""+ refund.getRefund_amount() +"\"," 
				+ "\"refund_reason\":\""+ refund.getRefund_reason() +"\"," 
				+ "\"out_request_no\":\""+ refund.getOut_request_no() +"\"}");
		try {
			result = alipayClient.execute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		System.out.println("支付宝退款：***********"+refund.getOut_trade_no());
		//获取session是否存在改签订单，
		Object obj = session.getAttribute("oldOrderNum");
		//不管是否存在移除session中的退款订单号
		session.removeAttribute("oldOrderNum");
		//获取session中的用户id
		Object userobj = session.getAttribute("user");
		Integer  userInfoId = 0;
		if(userobj!=null){
			UsersInfo usersInfo = (UsersInfo) userobj;      //转化对象
			userInfoId= usersInfo.getId();
		}
		//执行ordeservice中的退款方法(存在改签订单时，两个订单号都是一样的，在service中只需要将原订单退款删除，现订单支付)
		CinemaOder cinemaOder = new CinemaOder();
		cinemaOder.setOrdernum(refund.getOut_trade_no());                     //封装退款订单号
        orderService.returnOrder(cinemaOder,obj,newOderNum,userInfoId);      //数据库修改订单状态
		//返回订单页面
		return "redirect:/movieshow/userorder.html";
	}
	
	
	/**
	 * 查询支付接口。退款前需要查询.第三个参数为存在改签时的新订单,第四个参数是改签时的差价
	 * @return
	 */
	@RequestMapping("/query")
	public String query(QueryArg query, Model model,String newOderNum,String difAdjustedprice) {
		System.out.println("退款查询："+query.getOut_trade_no()+"新订单号："+newOderNum+"退款差价："+difAdjustedprice);
		//获得初始化的AlipayClient
		alipayClient = new DefaultAlipayClient(GatewayUrl, App_id, Merchant_private_key, "json", Charset, Alipay_public_key, Sign_type);
		//设置请求参数
		AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ query.getOut_trade_no() +"\","+"\"trade_no\":\""+ query.getTrade_no() +"\"}");
		try {
			result = alipayClient.execute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(result);
		String Jsonparams = jsonObject.getString("alipay_trade_query_response");
		jsonObject = JSONObject.fromObject(Jsonparams);
		//查询退款的各个参数
		String out_trade_no = jsonObject.getString("out_trade_no");        //查询订单号
		String trade_no = jsonObject.getString("trade_no");                //查询支付宝交易号
		String total_amount = jsonObject.getString("total_amount");        //查询退款金额
		//创建对象封装参数
		RefundArg refundArg = new RefundArg();
		refundArg.setOut_trade_no(out_trade_no);
		refundArg.setTrade_no(trade_no);
		refundArg.setRefund_amount(total_amount);   //正常退款订单的退款金额
		//判断是直接退款还是改签退款，如果是改签退款，则应该是退差价
		if(difAdjustedprice !=null){
			refundArg.setRefund_amount(difAdjustedprice);   //改签时退的差价
		}
		System.out.println("退款对象："+refundArg);
		//model域中存放数据
		model.addAttribute("refundArg",refundArg);
		model.addAttribute("newOderNum",newOderNum);
		//输出
		return "/movieshow/returnorder.html";
	}
	

	/**
	 * 退款查询
	 * @return
	 */
	@RequestMapping("/refundquery")
	@ResponseBody
	public String refundquery(RefundArg refund) {
		alipayClient =  new DefaultAlipayClient(GatewayUrl, App_id, Merchant_private_key, "json", Charset, Alipay_public_key, Sign_type);
		
		//设置请求参数
		AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ refund.getOut_trade_no() +"\"," 
				+"\"trade_no\":\""+ refund.getTrade_no() +"\","
				+"\"out_request_no\":\""+ refund.getOut_request_no() +"\"}");
		try {
			result = alipayClient.execute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		//输出
		return result;
	}
	
	
	/**
	 * 关闭交易接口
	 */
	@RequestMapping("/close")
	@ResponseBody
	public String close(QueryArg q) {
		alipayClient =  new DefaultAlipayClient(GatewayUrl, App_id, Merchant_private_key, "json", Charset, Alipay_public_key, Sign_type);		
		//设置请求参数
		AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
		
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ q.getOut_trade_no() +"\"," +"\"trade_no\":\""+ q.getTrade_no() +"\"}");
		try {
			result = alipayClient.execute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		System.out.println(result);
		//输出
		return result;
	}

	//支付成功之后执行的controller。该方法已被CinemaOrderController中的方法代替
	@RequestMapping("/toresult")
	public String toresult(String out_trade_no){
		System.out.println("显示结果："+out_trade_no);
		return "/movieshow/userorder";
	}
	
}
